package cool.zhang.config;

import cool.zhang.bean.Listen;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by chemeng on 2017/4/1.
 */
@org.springframework.context.annotation.Configuration
public class Configuration {

    private static Logger logger = LoggerFactory.getLogger(Configuration.class);

    /**
     * 注入消息容器
     *
     * @param redisConnectionFactory jedis连接池
     * @param listenerAdapter        监听适配器
     * @return bean
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory,
                                                   MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        //绑定监听者与信道的管理
        container.addMessageListener(listenerAdapter, new PatternTopic("java"));
        return container;
    }

    @Bean
    public MessageListenerAdapter adapter(Listen listen) {
        //指定监听者和监听方法
        return new MessageListenerAdapter(listen, "handleMsg");
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.redis")
    public JedisPoolConfig getRedisConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        return config;
    }

    @Bean
    public Listen getListen() {
        JedisPoolConfig config = new JedisPoolConfig();
        return new Listen();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.redis")
    public RedisConnectionFactory getConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        JedisPoolConfig config = getRedisConfig();
        factory.setPoolConfig(config);
        logger.info("JedisConnectionFactory bean init success.");
        return factory;
    }
}
